﻿using NLog;
using SQLitePCL;
using SSC.PlcConnect;
using SSC.Services;
using SSC.WebApi;
using System.Windows;

namespace SSC
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static SQLiteDatabaseService DatabaseService { get; private set; }
        protected async override void OnStartup(StartupEventArgs e)
        {
            // 初始化数据库服务
            string connectionString = "Data Source=E:\\Csharp\\SSC\\SSC\\Data\\SSCData.db";
            DatabaseService = new SQLiteDatabaseService(connectionString);
            // 初始化PLC连接
            try
            {
                string plcIpAddress = "192.168.2.1";
                int plcPort = 102;
                IPlcConnect plcConnection = PlcFactory.CreatePlcConnection(PlcType.Siemens, plcIpAddress, plcPort);
                bool isConnected = await plcConnection.ConnectAsync();
                if (isConnected)
                {
                    Variable.PlcConnectedStatus = true;
                    Variable.PlcConnection = plcConnection;
                    Console.WriteLine("PLC连接已成功建立。");
                }
                else
                {
                    Variable.PlcConnectedStatus = false;
                    Console.WriteLine("PLC连接失败。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"PLC连接初始化失败: {ex.Message}");
            }
            Batteries.Init();
            // 注册全局异常处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            // 启动嵌入式 Web API 服务
            ApiHost.Start();
            // 设置主窗口
            base.OnStartup(e);
        }

        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                // 记录异常到 NLog
                Logger.Error(ex, "未处理的异常");
            }
            MessageBox.Show("发生未处理的异常，请联系管理员！");
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            // 记录异常到 NLog
            Logger.Error(ex, "Dispatcher 未处理的异常");
            MessageBox.Show("发生未处理的异常，请联系管理员！");
            e.Handled = true;  // 标记异常已处理，防止应用程序崩溃
        }

    }

}
